package com.hrbu.springboot04.controller;

import com.hrbu.springboot04.utils.UploadFileUtil;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @Description:
 * @Author: tanyajun
 * @CreateTime: 2021/4/8
 * @Blog: https://tanyajun.top
 */
@Controller
public class UploadController {
    @GetMapping("/upload")
    public String toUpload(){
        return "views/upload";
    }
    @PostMapping("/upload")
    public String upload(@RequestPart("singleFile")MultipartFile singleFile, @RequestPart MultipartFile[] files) throws IOException {
        File local = UploadFileUtil.mkdirsByDate("E:/demo_upload");
        if(!local.exists()){
            local.mkdirs();
        }
        if(!singleFile.isEmpty()){
            singleFile.transferTo(new File(local.getAbsolutePath(),
                    UploadFileUtil.generateOriginalFilename(singleFile.getOriginalFilename())));
        }
        if(!StringUtils.isEmpty(files)){
            for (MultipartFile file : files) {
                file.transferTo(new File(local.getAbsolutePath(),
                        UploadFileUtil.generateOriginalFilename(file.getOriginalFilename())));
            }
        }
        return "ok";
    }
}
